import { NavigationActions, StackActions } from 'react-navigation'
import { isNetLink } from './NetUtils'

let _navigator

function setTopLevelNavigator (navigatorRef) {
  _navigator = navigatorRef
}

function netErrorGo (routeName, params) {
  return isNetLink().catch(error => {
    _navigator.dispatch(
      NavigationActions.navigate({
        routeName: 'NetError',
        params: {
          targetRouteName: routeName,
          targetParams: params
        }
      })
    )
    throw error
  })
}

/**
 * 跳转页面单例时调用该方法
 * @param routeName
 * @param params
 */
function navigate (routeName, params) {
  // netErrorGo(routeName, params).then(() => {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params
    })
  )
  // }).catch(() => {
  // })
}

/**
 * 跳转页面非单例时调用该方法
 * @param routeName
 * @param params
 */
function push (routeName, params) {
  // netErrorGo(routeName, params).then(() => {
  _navigator.dispatch(
    StackActions.push({
      routeName,
      params
    })
  )
  // }).catch(() => {
  // })
}

/**
 * 替换路由
 * @param routeName
 * @param params
 */
function replace (routeName, params) {
  _navigator.dispatch(
    StackActions.replace({
      routeName,
      params
    })
  )
}

/**
 * 返回
 * @param key
 */
function back (key) {
  _navigator.dispatch(
    NavigationActions.back({
      key: key
    })
  )
}

/**
 * 回到顶层
 */
function popToTop () {
  _navigator.dispatch(StackActions.popToTop())
  // _navigator.dispatch(StackActions.popToTop())
}

const NavigationService = {
  navigate,
  push,
  replace,
  back,
  popToTop,
  setTopLevelNavigator
}
export default NavigationService
